// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// DEMA Trend V2 - Clean version with trend labels

//@version=6
indicator("DEMA Flow [Alpha Extract]", overlay=true, behind_chart = false)

// ═══════════════════════════════════════════════════════════════
// INPUTS
// ═══════════════════════════════════════════════════════════════

// DEMA Settings
demaLength = input.int(23, "DEMA Length", minval=5, maxval=100, group="DEMA Trend")
hlFilterLength = input.int(4, "HL Median Filter Length", minval=3, maxval=15, group="DEMA Trend")

// ATR Band Settings (affects trend color)
atrLength = input.int(14, "ATR Length", minval=5, maxval=50, group="ATR Bands")
upperAtrMult = input.float(2.1, "Upper ATR Multiplier", minval=0.5, maxval=5.0, step=0.1, group="ATR Bands")
lowerAtrMult = input.float(1.5, "Lower ATR Multiplier", minval=0.5, maxval=5.0, step=0.1, group="ATR Bands")

// Display
showBands = input.bool(true, "Show ATR Bands", group="Display")
showLabels = input.bool(true, "Show Trend Labels", group="Display")

// ═══════════════════════════════════════════════════════════════
// CORE FUNCTION: DEMA
// ═══════════════════════════════════════════════════════════════

dema(series float src, simple int length) =>
    ema1 = ta.ema(src, length)
    ema2 = ta.ema(ema1, length)
    demaValue = 2 * ema1 - ema2
    demaValue

// ═══════════════════════════════════════════════════════════════
// CORE FUNCTION: HL MEDIAN FILTER
// ═══════════════════════════════════════════════════════════════

hlMedian(series float src, simple int length) =>
    var float median = na
    if bar_index >= length - 1
        window = array.new_float()
        for i = 0 to length - 1
            array.push(window, src[i])
        array.sort(window)
        lenW = array.size(window)
        median := lenW % 2 == 1 ?
                  array.get(window, lenW / 2) :
                  (array.get(window, lenW/2 - 1) + array.get(window, lenW/2)) / 2
    median

// ═══════════════════════════════════════════════════════════════
// CORE FUNCTION: ATR BANDS
// ═══════════════════════════════════════════════════════════════

atrBands(series float src, simple int atrLen, float upperMult, float lowerMult) =>
    atr = ta.atr(atrLen)
    upperBand = src + upperMult * atr
    lowerBand = src - lowerMult * atr
    [upperBand, lowerBand]

// ═══════════════════════════════════════════════════════════════
// CALCULATE INDICATORS
// ═══════════════════════════════════════════════════════════════

// 1. Calculate DEMA and apply HL median filter for smooth trend baseline
demaValue = dema(close, demaLength)
smoothDema = hlMedian(demaValue, hlFilterLength)

// 2. Calculate ATR Bands around the smoothed DEMA
[upperBand, lowerBand] = atrBands(smoothDema, atrLength, upperAtrMult, lowerAtrMult)

// ═══════════════════════════════════════════════════════════════
// SIGNAL GENERATION (Band breakout only)
// ═══════════════════════════════════════════════════════════════

// Band breakout signal
longSignal = close > upperBand
shortSignal = close < lowerBand

var trendSignal = 0

if longSignal
    trendSignal := 1

if shortSignal
    trendSignal := -1

// ═══════════════════════════════════════════════════════════════
// VISUALIZATION
// ═══════════════════════════════════════════════════════════════

// Color scheme
bullColor = color.new(#00ff88, 0)
bearColor = color.new(#ff0066, 0)
neutralColor = color.new(#888888, 50)

// Trend color
trendColor = trendSignal == 1 ? bullColor : trendSignal == -1 ? bearColor : neutralColor

// Plot DEMA trend line
plot(smoothDema, "Smooth DEMA Trend", color=trendColor, linewidth=2)

// Candle coloring based on trend
plotcandle(open, high, low, close, title="DEMA Trend Candles",
           color=trendColor, wickcolor=trendColor, bordercolor=trendColor, force_overlay=true)

// Bar coloring
barcolor(trendColor, title="Trend Bars")

// Trend change labels
bullishSignal = ta.crossover(trendSignal, 0)
bearishSignal = ta.crossunder(trendSignal, 0)

// ═══════════════════════════════════════════════════════════════
// ALERTS
// ═══════════════════════════════════════════════════════════════

alertcondition(bullishSignal, "DEMA Trend Bullish", "DEMA Trend: Turned Bullish ▲")
alertcondition(bearishSignal, "DEMA Trend Bearish", "DEMA Trend: Turned Bearish ▼")
